package com.fw.ui.util.validator;

import java.util.Calendar;
import java.util.Date;

import com.vaadin.data.Validator;
import com.vaadin.ui.DateField;

public class DateFromToValidator implements Validator {

    private static final long serialVersionUID = 1L;

    private String message;
    private DateField dateFieldFrom;
    private DateField dateFieldTo;
    
    public DateFromToValidator(String message, DateField dateFieldFrom, DateField dateFieldTo) {
	this.message = message;
	this.dateFieldFrom = dateFieldFrom;
	this.dateFieldTo = dateFieldTo;
    }

    @Override
    public void validate(Object value) throws InvalidValueException {
	Date dateFrom = dateFieldFrom.getValue();
	Date dateTo = dateFieldTo.getValue();
	
	if (dateFrom != null && dateTo != null){
	    Calendar calendarFrom = Calendar.getInstance();
	    Calendar calendarTo = Calendar.getInstance();
	    
	    calendarFrom.setTime(dateFrom);
	    calendarFrom.set(Calendar.HOUR_OF_DAY, 0);
	    calendarFrom.set(Calendar.MINUTE, 0);
	    calendarFrom.set(Calendar.SECOND, 0);
	    calendarFrom.set(Calendar.MILLISECOND, 0);
	    
	    calendarTo.setTime(dateTo);
	    calendarTo.set(Calendar.HOUR_OF_DAY, 23);
	    calendarTo.set(Calendar.MINUTE, 59);
	    calendarTo.set(Calendar.SECOND, 59);
	    calendarTo.set(Calendar.MILLISECOND, 999);
	    
	    
	    if (calendarFrom.after(calendarTo)){
		throw new InvalidValueException(message);
	    }
	    
	}
    }

}
